package com.atguigu.flink.charkoer07;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.client.program.StreamContextEnvironment;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.util.Date;
import java.util.HashMap;

public class FlinkWindows2 {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamContextEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        env.socketTextStream("hadoop162", 9999)
                .flatMap(new FlatMapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public void flatMap(String value, Collector<Tuple2<String, Integer>> out) throws Exception {
                        String[] line = value.split(" ");
                        for (String word : line) {
                            out.collect(Tuple2.of(word, 1));
                        }
                    }
                })
                .keyBy(x -> x.f0)
                .countWindow(3)
                .process(new ProcessWindowFunction<Tuple2<String, Integer>, String, String, GlobalWindow>() {

                    @Override
                    public void process(String s,
                                        Context context,
                                        Iterable<Tuple2<String, Integer>> elements,
                                        Collector<String> out) throws Exception {
                        HashMap<String, Integer> idToSum = new HashMap<>();

                        for (Tuple2<String, Integer> element : elements) {
                            Integer sum = idToSum.getOrDefault(s, 0);
                            sum += element.f1;
                            idToSum.put(s, sum);
                        }

                        out.collect(s + " " + idToSum.get(s));
                    }
                }).print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
